<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2018/11/29
 * Time: 17:53
 */
namespace common\logics\adminuser;

use common\widgets\Tool;
use yii\base\BaseObject;
use Yii;
use common\logics\auth\AuthLogic;
use common\services\jwt\JWT;


class AdminUserLogic extends BaseObject implements IAdminUser
{
    /** @var \common\sources\read\adminuser\AdminUserAccess $RAdminUserAccess **/
    private $RAdminUserAccess;
    /** @var \common\sources\write\adminuser\AdminUserAccess $WAdminUserAccess **/
    private $WAdminUserAccess;
    /** @var \common\sources\write\loginuserpower\LoginUserPowerAccess $WLoginUserPowerAccess */
    private $WLoginUserPowerAccess;
    /** @var \common\sources\read\smscode\SmsCodeAccess $RSmsCodeAccess * */
    private $RSmsCodeAccess;
    /** @var \common\sources\write\smscode\SmsCodeAccess $WSmsCodeAccess * */
    private $WSmsCodeAccess;
    /** @var \common\sources\read\loginrole\LoginRoleAccess $RLoginRoleAccess */
    private $RLoginRoleAccess;
    /** @var \common\sources\write\sendddcode\SendDdCodeAccess $WSendDdCodeAccess **/
    private $WSendDdCodeAccess;
    /** @var \common\sources\read\sendddcode\SendDdCodeAccess $RSendDdCodeAccess **/
    private $RSendDdCodeAccess;

    public function init()
    {
        $this->WLoginUserPowerAccess= Yii::$container->get('WLoginUserPowerAccess');
        $this->WAdminUserAccess = Yii::$container->get('WAdminUserAccess');
        $this->RAdminUserAccess = Yii::$container->get('RAdminUserAccess');
        $this->RSmsCodeAccess = Yii::$container->get("RSmsCodeAccess");
        $this->WSmsCodeAccess = Yii::$container->get("WSmsCodeAccess");
        $this->WSendDdCodeAccess = Yii::$container->get("WSendDdCodeAccess");
        $this->RSendDdCodeAccess = Yii::$container->get("RSendDdCodeAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }


    public function getList()
    {
        $list = $this->RAdminUserAccess->getList();
        return Tool::returnJson($list, 200, "成功");
    }

    public function addLoginUser($data)
    {
        if (empty($data['account'])) {
            return Tool::returnJson([], 401, "账号不能为空");
        }
        if (empty($data['username'])) {
            return Tool::returnJson([], 402, "用户名不能为空");
        }
        if (!(Tool::isEmail($data['email']))) {
            return Tool::returnJson([], 403, "邮箱不存在");
        }
        if (empty($data['role'])) {
            return Tool::returnJson([], 405, "请选择角色");
        }
        $login_user = $this->RAdminUserAccess->getDetial($data['account']);
        if (!empty($login_user)) {
            return Tool::returnJson([], 406, "登陆账号已经存在");
        }
        $result = $this->WAdminUserAccess->addLoginUser($data);
        if ($result) {
            return Tool::returnJson([], 200, "成功");
        }
        return Tool::returnJson([], 407, "失败");
    }

    public function modifyLoginUser($data)
    {
        if (!(Tool::isEmail($data['email']))) {
            return Tool::returnJson([], 403, "邮箱不存在");
        }
        if (empty($data['username'])) {
            return Tool::returnJson([], 406, "用户名不能为空");
        }
	    if (empty($data['role'])) {
		    return Tool::returnJson([], 405, "请选择角色");
	    }
        $login_user = $this->RAdminUserAccess->getLoginUserById($data['login_id']);
        if (empty($login_user)) {
            return Tool::returnJson([], 407, "登陆账号不存在");
        }
        $result = $this->WAdminUserAccess->modifyLoginUser($data);
        if ($result) {
            return Tool::returnJson([], 200, "成功");
        }
        return Tool::returnJson([], 408, "失败");
    }

    public function delLoginUser($data)
    {
        if (empty($data['login_id'])) {
            return Tool::returnJson([], 401, "登陆用户id不能为空");
        }
        if (empty($data['safetyCode'])) {
            return Tool::returnJson([], 402, "安全码不能为空");
        }
        if ($data['safetyCode'] != md5($data['login_id'])) {
            return Tool::returnJson([], 403, "安全码异常");
        }
        $user = $this->RAdminUserAccess->getLoginUserById($data['login_id']);
        if (empty($user)) {
            return Tool::returnJson([], 405, "该登陆用户不存在");
        }
        $result = $this->WAdminUserAccess->delLoginUser($data);
        if ($result) {
            //删除用户权限表记录
            $this->WLoginUserPowerAccess->delUserPower($data['login_id']);
            return Tool::returnJson([], 200, "成功");
        }
        return Tool::returnJson([], 406, "删除失败");
    }

    public function getAdminUser($data)
    {
	    if (empty($data['phone'])) {
		    return Tool::returnJson([], 401, "登陆手机不能为空");
	    }

	    // 密码登录 账号处理
    	if( $data['phone'] == 15664059581){
    		return $this->newLogin($data);
	    }

        if (empty($data['sms_code'])) {
            return Tool::returnJson([], 402, "验证码不能为空");
        }

        $adminUser = $this->RAdminUserAccess->getDetial($data['phone']);
        if(empty($adminUser)){
            return Tool::returnJson([],403,'用户不存在');
        }
        $smsArr = $this->RSmsCodeAccess->getSmsCode(['phone' => $data['phone'], 'type' => 4]);
        if (intval($smsArr['verifycode']) !== intval($data['sms_code'])) {
            return Tool::returnJson($data = [], $code = 405, '验证码输入有误');
        }
        //生成secrekey
        $secrekey = md5(time() . rand(1000, 99999999));
        $adminUser['secrekey'] = $secrekey;
        $this->WSmsCodeAccess->modifyCodeStatus($smsArr['id']);

        $loginid['login_id'] = $adminUser['id'];
        //将登录用户的id存入jwt
        $access_token = $this->jwtToken($loginid['login_id'], $data['phone']);
        $adminUser['access_token'] = $access_token;
        return Tool::returnJson($adminUser,200,"登陆成功");
    }

    //通过Jwt生成token
    public function jwtToken($userId, $phone)
    {
        $key = Yii::$app->params['access_key'];
        $time = time();
        $token = [
            'iat' => $time,//签收时间
            'nbf' => $time, //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time + 43200, //过期时间,这里设置2个小时
            'data' => [ //自定义信息，不要定义敏感信息
                'userid' => $userId,
                'phone' => $phone
            ]
        ];
        return JWT::encode($token, $key);
    }
    //推出登录
    public function logout()
    {
        $session = Yii::$app->session;
        $session->destroy('login_id');
        $session->destroy('phone');
        $session->destroy('is_login');
        return Tool::returnJson([], $code = 200, '退出成功');
    }

    //发送钉钉消息
    public function sendDD($data)
    {
        if(empty($data['operator']))
        {
            return Tool::returnJson([],406,"操作人不能为空");
        }
        $ramd = rand(100000,999999);
        $webhook = Yii::$app->params['sms_ddcode__url'];
        $message="日期：【".date("Y-m-d H:i:s",time())."】
描述:【管理员".$data['operator']. "正在进行" . $data['content'] . "操作】
验证码：【".$ramd."】";
        $param = array ('msgtype' => 'text','text' => array ('content' => $message),"at"=>["isAtAll" =>true]);
        $data_string = json_encode($param);
        $result = $this->request_by_curl($webhook, $data_string);
        $arr = json_decode($result,true);
        if($arr['errcode'] == 0)
        {
            //增加验证码记录
            $codeArr = [
                "phone" => $data['phone'],
                "code" => $ramd,
                "status" => 1,
                "operator" => $data['operator'],
            ];
            $this->WSendDdCodeAccess->sendDdCode($codeArr);
            return Tool::returnJson([],200,"发生钉钉成功");
        }else{
            return Tool::returnJson([],408,"发送钉钉失败");
        }
    }

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }


	/**
	 * newLogin 密码登录限定账号密码 【临时使用】
	 * @param $data
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/10
	 * @return false|string
	 */
    private function  newLogin($data){
		$pwd = '7777777';

	    if (empty($data['sms_code'])) {
		    return Tool::returnJson([], 402, "密码不能为空");
	    }
	    if ($data['sms_code'] != $pwd) {
		    return Tool::returnJson([], 402, "密码错误");
	    }

	    $adminUser = $this->RAdminUserAccess->getDetial($data['phone']);
	    if(empty($adminUser)){
		    return Tool::returnJson([],403,'用户不存在');
	    }
	    //生成secrekey
	    $secrekey = md5(time() . rand(1000, 99999999));
	    $adminUser['secrekey'] = $secrekey;

	    $loginid['login_id'] = $adminUser['id'];
	    //将登录用户的id存入jwt
	    $access_token = $this->jwtToken($loginid['login_id'], $data['phone']);
	    $adminUser['access_token'] = $access_token;
	    return Tool::returnJson($adminUser,200,"登陆成功");
    }
}